<template>
<div>
  <nav id="navbar" class="navbar navbar-expand-lg bg-body-tertiary bg-dark sticky-top" data-bs-theme="dark">
    <div class="container">
      <a class="navbar-brand" href="#home">Elysian Images</a>
      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link" href="#win11">Win11定制</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#win11-msdn">Win11官方</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#win10">Win10定制</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#win10-msdn">Win10官方</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#other">其他定制</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#other-msdn">其他定制</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#ubuntu">Ubuntu</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>
  <div data-bs-spy="scroll" data-bs-target="#navbar" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="container scrollspy-example bg-body-tertiary p-3 rounded-2" tabindex="0">
    
      <!-- IP类型检测结果显示 -->
    <div class="bg-info bg-opacity-10 p-3 rounded mb-4">
      <div class="d-flex justify-content-between items-center mb-2">
        <h3 class="mb-0">连接信息检测</h3>
        <button @click="recheckIPType" class="btn btn-sm btn-primary">
          重新检测
        </button>
      </div>
      <div class="row">
        <div class="col-md-4">
          <p class="mb-1"><strong>您的IP地址:</strong></p>
          <p class="font-monospace bg-light p-2 rounded">{{ userIP }}</p>
        </div>
        <div class="col-md-4">
          <p class="mb-1"><strong>IP类型:</strong></p>
          <p class="font-monospace bg-light p-2 rounded">{{ ipType }}</p>
        </div>
        <div class="col-md-4">
          <p class="mb-1"><strong>连接类型:</strong></p>
          <p class="font-monospace bg-light p-2 rounded">{{ connectionType }}</p>
        </div>
      </div>
      <p class="mt-3 text-sm text-muted">检测方式: {{ detectionMethod }}</p>
    </div>
    
    <!-- 其他内容保持不变 -->
    <div class="text-center py-12">
      <h2 id="home" class="text-3xl font-bold text-primary">Coming Soon</h2>
      <p class="mt-4 text-muted">敬请期待，即将上线！</p>
    </div>
    
    <div class="text-center py-8">
      <h2 id="win11" class="text-2xl font-bold text-primary">Win11定制</h2>
      <p class="mt-4">Windows 11 定制版本，优化性能，提升使用体验</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('win11', 'custom')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('win11', 'custom')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="win11-msdn" class="text-2xl font-bold text-primary">Win11官方</h2>
      <p class="mt-4">Windows 11 官方原版，纯净无修改</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('win11', 'msdn')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('win11', 'msdn')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="win10" class="text-2xl font-bold text-primary">Win10定制</h2>
      <p class="mt-4">Windows 10 定制版本，优化性能，提升使用体验</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('win10', 'custom')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('win10', 'custom')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="win10-msdn" class="text-2xl font-bold text-primary">Win10官方</h2>
      <p class="mt-4">Windows 10 官方原版，纯净无修改</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('win10', 'msdn')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('win10', 'msdn')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="other" class="text-2xl font-bold text-primary">其他定制</h2>
      <p class="mt-4">其他操作系统定制版本</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('other', 'custom')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('other', 'custom')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="other-msdn" class="text-2xl font-bold text-primary">其他定制</h2>
      <p class="mt-4">其他操作系统官方原版</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('other', 'msdn')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('other', 'msdn')">校验值</button>
      </div>
    </div>
    
    <div class="text-center py-8">
      <h2 id="ubuntu" class="text-2xl font-bold text-primary">Ubuntu</h2>
      <p class="mt-4">Ubuntu Linux 系统镜像</p>
      <div class="mt-6">
        <button class="btn btn-primary mx-2" @click="generateS3Link('ubuntu', 'custom')">下载链接</button>
        <button class="btn btn-secondary mx-2" @click="showChecksum('ubuntu', 'custom')">校验值</button>
      </div>
    </div>
  </div>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// IP信息相关的响应式数据
const userIP = ref('获取中...');
const ipType = ref('未知'); // 将返回 "IPv4", "IPv6" 或 "未知"
const connectionType = ref('检测中...');
const detectionMethod = ref('初始化中...'); // 记录使用的检测方法

/**
 * 直接检测网络连接类型的方法
 * 通过尝试连接到IPv4和IPv6端点来确定优先连接类型
 */
const detectNetworkConnectionType = () => {
  return new Promise((resolve) => {
    console.log('开始网络连接类型检测');
    
    // 创建一个计数器，用于跟踪完成的检测数量
    let detectionCount = 0;
    const totalDetections = 2;
    
    // 结果对象
    const results = {
      ipv4Success: false,
      ipv6Success: false,
      ipv4Time: Infinity,
      ipv6Time: Infinity
    };
    
    // 检查是否支持IPv4连接
    const testIPv4 = () => {
      const startTime = performance.now();
      const xhr = new XMLHttpRequest();
      
      // 使用一个公共的IPv4-only端点进行测试
      xhr.open('GET', 'https://1.1.1.1/cdn-cgi/trace', true);
      xhr.timeout = 1500; // 设置超时时间为1.5秒
      
      xhr.onload = () => {
        results.ipv4Success = true;
        results.ipv4Time = performance.now() - startTime;
        console.log('IPv4连接测试成功，响应时间:', results.ipv4Time);
        checkCompletion();
      };
      
      xhr.onerror = () => {
        console.log('IPv4连接测试失败');
        checkCompletion();
      };
      
      xhr.ontimeout = () => {
        console.log('IPv4连接测试超时');
        checkCompletion();
      };
      
      try {
        xhr.send();
      } catch (e) {
        console.log('IPv4连接测试异常:', e);
        checkCompletion();
      }
    };
    
    // 检查是否支持IPv6连接
    const testIPv6 = () => {
      const startTime = performance.now();
      const xhr = new XMLHttpRequest();
      
      // 使用一个公共的IPv6-only端点进行测试
      xhr.open('GET', 'https://[2606:4700:4700::1111]/cdn-cgi/trace', true);
      xhr.timeout = 1500; // 设置超时时间为1.5秒
      
      xhr.onload = () => {
        results.ipv6Success = true;
        results.ipv6Time = performance.now() - startTime;
        console.log('IPv6连接测试成功，响应时间:', results.ipv6Time);
        checkCompletion();
      };
      
      xhr.onerror = () => {
        console.log('IPv6连接测试失败');
        checkCompletion();
      };
      
      xhr.ontimeout = () => {
        console.log('IPv6连接测试超时');
        checkCompletion();
      };
      
      try {
        xhr.send();
      } catch (e) {
        console.log('IPv6连接测试异常:', e);
        checkCompletion();
      }
    };
    
    // 检查是否所有测试都已完成
    const checkCompletion = () => {
      detectionCount++;
      if (detectionCount >= totalDetections) {
        // 分析结果并返回
        let connectionType = '未知';
        
        if (results.ipv6Success && results.ipv4Success) {
          // 两种类型都支持，选择响应更快的
          connectionType = results.ipv6Time <= results.ipv4Time ? 'IPv6优先' : 'IPv4优先';
        } else if (results.ipv6Success) {
          connectionType = '仅IPv6';
        } else if (results.ipv4Success) {
          connectionType = '仅IPv4';
        }
        
        console.log('网络连接类型检测完成:', connectionType);
        resolve(connectionType);
      }
    };
    
    // 启动测试
    testIPv4();
    testIPv6();
    
    // 确保即使测试超时也能返回结果
    setTimeout(() => {
      if (detectionCount < totalDetections) {
        console.log('网络连接类型检测超时，返回部分结果');
        
        let connectionType = '检测超时';
        if (results.ipv6Success && results.ipv4Success) {
          connectionType = results.ipv6Time <= results.ipv4Time ? 'IPv6优先' : 'IPv4优先';
        } else if (results.ipv6Success) {
          connectionType = '仅IPv6';
        } else if (results.ipv4Success) {
          connectionType = '仅IPv4';
        }
        
        resolve(connectionType);
      }
    }, 2000);
  });
};

/**
 * 检测IP类型的方法 - 不使用第三方网站
 * 使用WebRTC API和浏览器内置功能来检测连接类型
 */
const detectIPType = () => {
  console.log('开始IP类型检测');
  detectionMethod.value = 'WebRTC + 网络连接测试';
  
  // 首先尝试WebRTC方法
  try {
    // 配置ICE服务器以提高IP地址暴露的可能性
    const configuration = {
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
      ],
      iceCandidatePoolSize: 10
    };
    
    // 创建RTCPeerConnection对象
    const pc = new RTCPeerConnection(configuration);
    
    // 创建数据通道
    pc.createDataChannel('');
    
    // 设置ICE状态监听
    pc.oniceconnectionstatechange = () => {
      console.log('ICE连接状态:', pc.iceConnectionState);
    };
    
    // 监听ICE候选事件，这是获取IP的关键
    let hasFoundIP = false;
    let iceCandidatesReceived = 0;
    
    pc.onicecandidate = (event) => {
      iceCandidatesReceived++;
      console.log('收到ICE候选 #' + iceCandidatesReceived + ':', event.candidate ? event.candidate.candidate : 'null');
      
      if (event.candidate) {
        const candidateInfo = event.candidate.candidate;
        
        // 尝试匹配IPv4地址
        const ipv4Regex = /\b(?:\d{1,3}\.){3}\d{1,3}\b/;
        const ipv4Match = candidateInfo.match(ipv4Regex);
        
        // 尝试匹配IPv6地址
        const ipv6Regex = /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,7}:|\b(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}\b|\b(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}\b|\b(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}\b|\b[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})\b|\b:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)\b|\bfe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}\b|\b::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1{0,1}[0-9]){0,1}[0-9])\b|\b[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})\b/;
        const ipv6Match = candidateInfo.match(ipv6Regex);
        
        // 优先使用找到的第一个IP地址
        if (ipv4Match && !hasFoundIP) {
          userIP.value = ipv4Match[0];
          ipType.value = 'IPv4';
          connectionType.value = 'IPv4连接 (WebRTC)';
          hasFoundIP = true;
          console.log('检测到IPv4地址:', ipv4Match[0]);
        } else if (ipv6Match && !hasFoundIP) {
          userIP.value = ipv6Match[0];
          ipType.value = 'IPv6';
          connectionType.value = 'IPv6连接 (WebRTC)';
          hasFoundIP = true;
          console.log('检测到IPv6地址:', ipv6Match[0]);
        }
      } else {
        // ICE候选收集完成
        console.log('ICE候选收集完成，共收到 ' + iceCandidatesReceived + ' 个候选');
        if (!hasFoundIP && ipType.value === '未知') {
          console.log('WebRTC未检测到IP，尝试备用方法');
          fallbackIPDetection();
        }
        // 关闭连接
        setTimeout(() => {
          pc.close();
        }, 500);
      }
    };
    
    // 创建并设置本地描述
    pc.createOffer()
      .then(offer => {
        return pc.setLocalDescription(offer);
      })
      .then(() => {
        console.log('WebRTC本地描述已设置');
      })
      .catch(err => {
        console.error('WebRTC操作失败:', err);
        fallbackIPDetection();
      });
    
    // 设置超时，确保即使WebRTC长时间无响应也能继续
    setTimeout(() => {
      console.log('WebRTC检测超时检查');
      if (ipType.value === '未知') {
        fallbackIPDetection();
      }
      if (pc.iceConnectionState !== 'closed') {
        pc.close();
      }
    }, 4000); // 增加超时时间以确保有足够时间收集候选
  } catch (error) {
    console.error('WebRTC检测失败:', error);
    // 如果WebRTC不可用，使用备用方法
    fallbackIPDetection();
  }
};

/**
 * 备用IP检测方法 - 当WebRTC不可用时使用
 * 使用浏览器内置API和网络相关信息
 */
const fallbackIPDetection = () => {
  console.log('执行备用IP检测方法');
  detectionMethod.value = '网络连接测试 + 智能推断';
  
  try {
    // 方法1: 检查window.location.hostname
    const hostname = window.location.hostname;
    console.log('当前主机名:', hostname);
    
    // 如果hostname是IP地址格式
    if (hostname.includes(':')) {
      // 包含冒号，可能是IPv6地址
      userIP.value = hostname;
      ipType.value = 'IPv6';
      connectionType.value = '可能使用IPv6连接';
      return;
    } else if (/^\d{1,3}\.(\d{1,3}\.){2}\d{1,3}$/.test(hostname)) {
      // 匹配IPv4格式
      userIP.value = hostname;
      ipType.value = 'IPv4';
      connectionType.value = '可能使用IPv4连接';
      return;
    }
    
    // 方法2: 执行网络连接类型直接检测
    detectNetworkConnectionType().then(networkTypeResult => {
      console.log('网络连接类型检测结果:', networkTypeResult);
      
      // 方法3: 使用Network Information API（如果可用）
      let networkInfoStr = '';
      if ('connection' in navigator && navigator.connection) {
        const networkInfo = navigator.connection;
        networkInfoStr = `网络类型: ${networkInfo.effectiveType || '未知'}`;
        console.log('网络信息:', networkInfoStr);
      }
      
      // 方法4: 基于浏览器和平台特性的智能推断
      const userAgent = window.navigator.userAgent;
      const platform = window.navigator.platform;
      
      // 检测是否为移动设备
      const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
      
      // 检测浏览器类型
      const isChrome = /Chrome|Chromium/i.test(userAgent);
      const isFirefox = /Firefox/i.test(userAgent);
      const isSafari = /Safari/i.test(userAgent) && !isChrome;
      const isEdge = /Edg/i.test(userAgent);
      
      // 进行更智能的IP类型推断，优先使用网络连接测试结果
      let ipTypeGuess = '未知';
      let connectionGuess = [];
      
      // 优先使用网络连接测试结果
      if (networkTypeResult && networkTypeResult !== '未知' && networkTypeResult !== '检测超时') {
        // 基于网络测试结果确定IP类型
        if (networkTypeResult.includes('IPv6')) {
          ipTypeGuess = networkTypeResult === '仅IPv6' ? 'IPv6' : 'IPv6优先';
        } else if (networkTypeResult.includes('IPv4')) {
          ipTypeGuess = networkTypeResult === '仅IPv4' ? 'IPv4' : 'IPv4优先';
        }
        connectionGuess.push(`网络测试: ${networkTypeResult}`);
      } else {
        // 网络测试失败，进行智能推断
        if (isChrome || isFirefox || isEdge) {
          // 现代浏览器通常优先使用IPv6（如果网络支持）
          ipTypeGuess = '可能优先使用IPv6';
          connectionGuess.push('现代浏览器');
        } else if (isSafari) {
          ipTypeGuess = '可能支持IPv6';
          connectionGuess.push('Safari浏览器');
        }
      }
      
      // 结合平台信息
      if (platform.includes('Win64') || platform.includes('MacIntel')) {
        connectionGuess.push('桌面平台');
      } else if (isMobile) {
        connectionGuess.push('移动设备');
      }
      
      // 结合网络信息
      if (networkInfoStr) {
        connectionGuess.push(networkInfoStr);
      }
      
      // 如果无法确定具体类型，提供一些有用信息
      if (ipTypeGuess === '未知') {
        userIP.value = '通过域名访问，综合检测结果';
        ipTypeGuess = '基于连接特征推断';
      } else {
        userIP.value = '通过网络连接测试推断';
      }
      
      // 最终赋值
      ipType.value = ipTypeGuess;
      connectionType.value = connectionGuess.join(' | ') || '无法确定连接类型';
      
      console.log('备用检测完成 - IP类型推断:', ipTypeGuess, '连接信息:', connectionType.value);
    }).catch(e => {
      console.log('网络连接类型检测异常:', e);
      
      // 即使网络检测失败，也要提供基本信息
      userIP.value = '通过域名访问，无法直接确定';
      ipType.value = '需要更高级检测';
      connectionType.value = '无法确定连接类型';
    });
  } catch (error) {
    console.error('备用检测方法失败:', error);
    userIP.value = '无法获取';
    ipType.value = '检测失败';
    connectionType.value = '无法确定连接类型';
  }
};

/**
 * 获取访问者IP类型的公共方法
 * @returns {string} 返回访问者的IP类型："IPv4", "IPv6" 或 "未知"
 */
const getVisitorIPType = () => {
  return ipType.value;
};

/**
 * 重新检测IP类型的方法
 */
const recheckIPType = () => {
  userIP.value = '重新获取中...';
  ipType.value = '未知';
  connectionType.value = '检测中...';
  detectionMethod.value = '初始化中...';
  detectIPType();
};

// 暴露方法供外部组件使用
defineExpose({
  getVisitorIPType,
  recheckIPType,
  detectNetworkConnectionType,
  userIP,
  ipType,
  connectionType,
  detectionMethod
});

// 组件挂载时执行IP检测
onMounted(() => {
  detectIPType();
});
</script>

<style scoped>
</style>